import Mocha from '../../../modules/mocha.js';
import Util from '../../../modules/util.js';
import SendMessage from '../../../modules/send_message.js';
import CheckFocusAccount from '../../../modules/check_focus_account.js';
import RTLog from '../../../modules/rt_log.js';

Page({
    data: {
        linkList: [],
        allLinkList: [],
        lookedLinkList: [],
        customErrorPopup: false,
        errContext: ''
    },
    pageNo: 0,
    pageSize: 10,
    baseUrl: `https://api.ali-fc.moapp.net.cn/check_url`,
    onLoad() {
        this.getConfig();
    },
    onShow() {
        if (this.data.lookedLinkList.length > 0) {
            this.changeSingerAccountStatus(this.data.lookedLinkList[0]);
        }
    },
    onPullDownRefresh() {
        wx.showNavigationBarLoading();
        this.getConfig().then(() => {
            wx.stopPullDownRefresh();
            wx.hideNavigationBarLoading();
        });
    },
    onReachBottom() {
        this.getAccoutLink().then((List) => {
            this.checkLinkAvailable(List);
        });
    },
    getAccoutLink() {
        return new Promise((resolve, reject) => {
            let showListLast = this.data.linkList.slice(-1)[0];
            let listLast = this.data.allLinkList.slice(-1)[0];
            if (showListLast === listLast) {
                this.pageNo = 0;
            }
            let newLinkList = this.data.linkList.concat(
                this.data.allLinkList.slice(
                    0 + this.pageNo * this.pageSize,
                    this.pageSize + this.pageNo * this.pageSize
                )
            );
            this.setData({
                linkList: newLinkList.map((item) => {
                    return {
                        ...item,
                        url: Util.formatUrl(item.url)
                    };
                })
            });
            this.pageNo = this.pageNo + 1;
            resolve(this.data.linkList);
        });
    },
    testLink(evt) {
        let { url, appid } = evt.currentTarget.dataset.item;
        this.setData({
            lookedLinkList: this.data.lookedLinkList.concat({ appid, url })
        });
        wx.navigateTo({
            url: `/pages/web/web?accountUrl=${url}&linked=true`
        });
    },
    changeSingerAccountStatus(item) {
        if (!item) {
            this.getConfig();
            return;
        }
        wx.showNavigationBarLoading();
        return new Promise((resolve, reject) => {
            let { appid, url } = item;
            const queryData = {
                url,
                mini_name: '织图机',
                appid
            };
            SendMessage.request(this.baseUrl, 'POST', queryData).then((invalidRes) => {
                let newList = this.data.linkList.map((item) => {
                    if (item.appid === appid) {
                        return {
                            ...item,
                            invalid_status: invalidRes.invalid
                        };
                    } else {
                        return item;
                    }
                });
                this.setData(
                    {
                        linkList: newList
                    },
                    () => {
                        CheckFocusAccount.request(
                            'GET',
                            `${getApp().mox.user.unionid}?appid=${appid}`
                        )
                            .then((res) => {
                                let newLinkList = this.data.linkList.map((item) => {
                                    if (item.appid === appid) {
                                        return {
                                            ...item,
                                            focus_status: res[0]?.status
                                        };
                                    } else {
                                        return item;
                                    }
                                });
                                this.setData({
                                    linkList: newLinkList,
                                    lookedLinkList: []
                                });
                                resolve(this.data.linkList);
                            })
                            .catch((err) => {
                                reject(err);
                            }).finally(() => {
                                wx.stopPullDownRefresh();
                                wx.hideNavigationBarLoading();
                            })
                    }
                );
            });
        });
    },
    getConfig() {
        wx.showLoading({
            title: '加载中...',
            mask: true
        });
        return new Promise((resolve, reject) => {
            Mocha.getConfig()
                .then((cfg) => {
                    this.setData({
                        allLinkList: Object.values(cfg.link_list).flat(Infinity)
                    });
                    this.getAccoutLink().then((List) => {
                        this.checkLinkAvailable(List);
                        resolve(List);
                    });
                    getApp().mox.stat(`liketest page get_mocha_h5_config success`);
                })
                .catch((err) => {
                    wx.hideLoading();
                    // getApp().mox.stat(
                    //     `liketest page get_mocha_h5_config fail：${err.msg || err.errMsg || '未知错误'}`
                    // );
                    getApp().mox.stat(`liketest page get_mocha_h5_config fail`);
                    RTLog.error(
                        'liketest page get_mocha_h5_config fail：',
                        err.errMsg || err.msg || '未知错误'
                    );
                    this.setData({
                        errContext: '获取mocha配置失败',
                        customErrorPopup: true
                    });
                    reject(err);
                });
        });
    },
    checkLinkAvailable(linkList) {
        if (!linkList) return;
        let newArr = [];
        let arr = [];
        return new Promise((resolve, reject) => {
            if (linkList.length) {
                linkList.forEach((item) => {
                    const queryData = {
                        url: item.url,
                        mini_name: '织图机',
                        appid: item.appid
                    };
                    arr.push({
                        orgin: item,
                        request: SendMessage.request(this.baseUrl, 'POST', queryData)
                    });
                });
                Promise.all(arr.map((b) => b.request))
                    .then((res) => {
                        res.forEach((itemInvalid, index) => {
                            newArr.push({
                                ...arr[index].orgin,
                                invalid_status: itemInvalid.invalid
                            });
                        });
                        this.checkUserFocusStatus(newArr);
                        getApp().mox.stat(`check_allAccount_available_status success`);
                    })
                    .catch((err) => {
                        wx.hideLoading();
                        // getApp().mox.stat(
                        //     `check_allAccount_available_status fail：${
                        //         err.msg || err.errMsg || '未知错误'
                        //     }`
                        // );
                        getApp().mox.stat(`check_allAccount_available_status fail`);
                        RTLog.error(
                            'check_allAccount_available_status fail：',
                            err.errMsg || err.msg || '未知错误'
                        );
                        this.setData({
                            errContext: 'o(╥﹏╥)o，检测公众号文章链接失败',
                            customErrorPopup: true
                        });
                        reject(err);
                    });
            }
        });
    },
    checkUserFocusStatus(focusArr) {
        if (!focusArr) return;
        let newArr = [];
        let arr = [];
        return new Promise((resolve, reject) => {
            if (focusArr.length) {
                focusArr.forEach((item) => {
                    arr.push({
                        origin: item,
                        request: CheckFocusAccount.request(
                            'GET',
                            `${getApp().mox.user.unionid}?appid=${item.appid}`
                        )
                    });
                });
                Promise.all(arr.map((reqRes) => reqRes.request))
                    .then((res) => {
                        res.forEach((items, index) => {
                            let orginItem = arr[index].origin;
                            newArr.push({
                                ...orginItem,
                                focus_status: items.length ? items[0].status : 2
                            });
                        });
                        wx.hideLoading();
                        this.setData({
                            linkList: newArr
                        });
                        getApp().mox.stat(`check_allAccount_focus_status success`);
                        resolve(newArr);
                    })
                    .catch((err) => {
                        wx.hideLoading();
                        // getApp().mox.stat(
                        //     `check_allAccount_focus_status fail：${
                        //         err.msg || err.errMsg || '未知错误'
                        //     }`
                        // );
                        getApp().mox.stat(`check_allAccount_focus_status fail`);
                        RTLog.error(
                            'check_allAccount_focus_status fail：',
                            err.errMsg || err.msg || '未知错误'
                        );
                        this.setData({
                            errContext: 'o(╥﹏╥)o，检测公众号关注状态失败',
                            customErrorPopup: true
                        });
                        reject(err);
                    });
            }
        });
    },
});
